import { Text, View, StyleSheet, Image , NativeModules,DeviceEventEmitter,StatusBar, TouchableOpacity,ScrollView} from 'react-native'
import React, { Component} from 'react'
import {Toast, Button,InputItem, Modal as AntdModal} from '@ant-design/react-native';
import RFIDItem from "../../components/RFIDItem/RFIDItem";
import { px2dp, px2dpW, px2sp } from '../../utils/DisplayUtils';
import {getTidInfoAPI,bindRFIDApi} from "../../api/AppApi"
import TouchHistoryMath from 'react-native/Libraries/Interaction/TouchHistoryMath';
export default class RFIDPage extends Component {

    constructor(props){
        super(props);
        this.state = {
          searchValue: '',
          rfid: '',
          tidInfo:{},
          isReset: true  //是否重置，重置显示扫描页
        };

    }


    componentDidMount(){

        DeviceEventEmitter.addListener('didGetRFID',(res)=>{
       
            console.log("rn didGetRFID:", res)
            this.setState({rfid: res})
           
    
          })

          NativeModules.RFIDModule.startScanRFID((res)=>{
            console.log("rn startScanRFID:", res)
            this.setState({rfid: res})
           
          
          }, (err)=>{
            console.log("rn startScanRFID err:", err)
          })

         
    

    }

    componentWillUnmount(){

        NativeModules.RFIDModule.stopScanRFID((res)=>{

        }, (err)=>{
  
        })


        DeviceEventEmitter.removeAllListeners('didGetRFID')
    }


    callScan(){

  

      const that = this;
      this.props.navigation.navigate('DefaultScanCodePage', {callBack:(res)=>{

        console.log("DefaultScanCodePage:", res)

        that.setState({searchValue:res})

        that.getTieInfocall(res)
        
      }});

    }


  getTieInfocall(theId){

  //   didGetTieInfo: {
  //     "Context": 
  //   {"InvOrgId": 8010, 
  //   "Ticket": "cpjL6hheb0D7hr381wR5VySI4FlE/sP9"
  // },
  //    "Message": null,
  //     "Result": {"barcode": "RF2613360148374", 
  //     "batchNo": "10203A0008",
  //      "id": "8e1f7cd54bc948a999eef3cc289e0a3b",
  //       "itemCode": "1100001861", 
  //       "itemDesc": "PVC-GY.205-16x1.0-160(4x40)-白色", 
  //       "qty": 160, 
  //       "workOrderNo": "1000002888"},
  //      "Success": true}
  
    const that = this

    getTidInfoAPI(theId).then(async (resp)=>{
        console.log("didGetTieInfo:", resp)

        if(resp.Result != null && resp.Result != undefined){

          that.setState({tidInfo: resp.Result, isReset: false})
          
        }

        

      
    }, (error)=>{
      Toast.info(error)
    }).catch((error)=>{
    //  ToastUtils.showToast( error);
    Toast.info("调用出错")
   });

  }

  bindRFIDCall(){

    bindRFIDApi(this.state.tidInfo.id, this.state.rfid).then((resp)=>{

      console.log(resp)

      Toast.info('绑定成功')

      this.reset()

    },(error)=>{
      Toast.info(error)
    })
  }
  


  reset(){
    this.setState({isReset: true, tidInfo: {}, rfid:'', searchValue:''})
  }

    



  render() {
    
    //扫描页面
    if(this.state.isReset){
      return (
        <View style={styles.container}>
        
          <View style={styles.searchBgView}>

            <View style = {styles.barcodeInputBgView}>

              <TouchableOpacity activeOpacity={0.5} onPress={() => this.callScan()} style={styles.search_icon}>
                <Image style = {{width:20, height: 20}} source={require("../../resource/images/search_icon.png")}  onPress={() => this.callScan()}></Image>
              </TouchableOpacity>

              <View style={styles.InputItemBgView}>

                <InputItem 
                    // clear
                    placeholder={'请输入物流编码'}
                    placeholderTextColor={'#999999'}
                    value={this.state.searchValue}
                    style={styles.textInput}
                    last={true}
                    onChange={val => {

                      this.setState({searchValue: val})

                      console.log(val.length)
                      if(val.length >= 15){
                        this.getTieInfocall(val)
                      }
                      
                    }}
                  ></InputItem>
                </View>

               
  

            </View>

            <TouchableOpacity activeOpacity={0.5} onPress={() => this.callScan()} style={styles.scanBtn}>
               <Image style = {{width:138, height: 138}} source={require("../../resource/images/saoma.png")}  onPress={() => this.callScan()}></Image>
            </TouchableOpacity>

           

            {/* <TouchableOpacity activeOpacity={0.5} onPress={() => this.callScan()} style={styles.scanBtn}>
               <Image style = {{width:296, height: 328}} source={require("../../resource/images/im_default.png")}  onPress={() => this.callScan()}></Image>
            </TouchableOpacity> */}

          </View>

          
          <View style={styles.backgroundSplitView}>

            <Image style = {{width:px2dp(375), height: px2dp(78)}} source={require("../../resource/images/back_search.png")}  onPress={() => this.callScan()}></Image>

          </View>
          

         
          {/* 默认底图 */}
          <View style={styles.defaultIconBg}>
              <Image style = {{width:px2dp(155), height: px2dp(202)}} source={require("../../resource/images/no_record.png")}  onPress={() => this.callScan()}></Image>
              <Text>暂无数据，请扫码!</Text>

          </View>



        </View>

      )
    }else{

      //扫描结果页面
      return (

      
        <View style={styles.container}>
  
          <StatusBar
            animated={true}
            translucent={true}
            barStyle={'dark-content'}
            backgroundColor={'transparent'}
          />
  
        <ScrollView style={styles.scrollViewBg}>
  
        
  
        
        <View style={styles.basicInfoView}>
            <RFIDItem theKey="生产订单：" theValue={this.state.tidInfo.workOrderNo}></RFIDItem>
            <RFIDItem theKey="生产批号：" theValue={this.state.tidInfo.batchNo}></RFIDItem>
            <RFIDItem theKey="物料编码：" theValue={this.state.tidInfo.itemCode}></RFIDItem>
            <RFIDItem theKey="物流码：" theValue={this.state.tidInfo.barcode}></RFIDItem>
            <RFIDItem theKey="物料描述：" theValue={this.state.tidInfo.itemDesc}></RFIDItem>
            <RFIDItem theKey="管材数量：" theValue={this.state.tidInfo.qty +"米" }></RFIDItem>
            <RFIDItem theKey="包装长度：" theValue={this.state.tidInfo.packageQty +"米" }></RFIDItem>
            <RFIDItem theKey="检验员：" theValue={this.state.tidInfo.inspector}></RFIDItem>

        </View>
        <View style ={styles.splitLineView}></View>

        <View style={styles.rfidBgView}>
           <RFIDItem theKey="RFID TID：" theValue={this.state.rfid}></RFIDItem>
        </View>  
          
          </ScrollView>
  
  
            <View style={styles.buttonBg}>
              
            <Button style={styles.leftButton} onPress={()=>{
                this.reset()
              }}>重置</Button>
            <Button style={styles.rightButton}  type="primary" onPress={()=>{

              if(this.state.rfid == '' || this.state.rfid == null || this.state.rfid == undefined){
                Toast.info('RFID不能为空，请扫描RFID')

                return
              }

              this.bindRFIDCall()

            }

            }>提交</Button>
            </View>
        </View>
      )
    }
    
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    // paddingTop: Platform.OS === 'android' ? StatusBar.currentHeight : 0,
    flexDirection: 'column',
    backgroundColor: '#dedede'
    
  },
  searchBgView:{

    height: px2dp(205),
    flexDirection:'column',
    backgroundColor:'#fff',
    zIndex: 100

  },

  barcodeInputBgView:{



    flexDirection:'row',
    height: px2dp(44),
    marginTop: px2dp(20),
    borderColor: "#dedede",
    borderWidth: 1,
    marginLeft: 12,
    marginRight: 12,
    borderRadius: px2dp(22),
    backgroundColor: '#dedede',
    alignItems:'center',
    

  },

  search_icon:{

    flex: 0,
    height: px2dp(20),
    marginLeft: px2dp(12),
    width:px2dp(20),
    alignItems:'center',
    justifyContent:'center',
    flex: 0

  },

  InputItemBgView:{

    height: px2dp(44),

    flex: 1

  },

  scanBtn:{
    height: px2dp(138),
    alignItems:'center',
    justifyContent:'center',
    marginTop: px2dp(10),
   
    
    
  },

  backgroundSplitView:{

    zIndex: 1,
    marginTop: px2dp(-10)
  },

  defaultIconBg:{

    flexDirection: 'column',
    alignItems:'center',
  },



  // 下面为扫码结果样式

  scrollViewBg:{
    flex: 1,
    backgroundColor: '#fff'
  },

  basicInfoView:{

    marginTop: px2dp(20),
    marginLeft:px2dp(32),
    marginRight:px2dp(32)

  },

  splitLineView:{
    height: px2dp(1),
    marginTop: px2dp(10),
    marginLeft:px2dp(32),
    marginRight:px2dp(32),
    backgroundColor:'#dedede'
  },

  rfidBgView:{
    marginTop: px2dp(10),
    marginLeft:px2dp(32),
    marginRight:px2dp(32),
    height: px2dp(80),
  },

  
  buttonBg:{
    
    marginTop: px2dp(10),
    
    height: px2dp(74),
    flexDirection: 'row',
    justifyContent: 'space-between',
    backgroundColor:'#fff'
  },

  leftButton:{
    flex: 1,
    marginLeft: px2dp(20),
    marginBottom:px2dp(30),
    marginTop: px2dp(10),
    height: px2dp(40)

  },
  rightButton:{
    flex: 1,
    marginLeft: px2dp(20),
    marginRight: px2dp(20),
    marginBottom:px2dp(30),
    marginTop: px2dp(10),
    height: px2dp(40),
    backgroundColor:'#0081cc',
    color:'#fff'

  },


  textInput: {
    height: px2dp(44),
    color: '#333',
    fontSize: 15,
  },
 
})